package com.net.core.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.net.core.config.AppContextUtils;
import io.swagger.annotations.ApiModelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class MyUtils {

    private static final Logger log = LoggerFactory.getLogger(MyUtils.class);

    public static <T> T getBean(Class<T> clazz) {
        return AppContextUtils.getBean(clazz);
    }

    public static <T> List<T> copyList(List obj, Class<T> clz) {
        JSONArray array = (JSONArray) JSONArray.toJSON(obj);
        List<T> list = array.toJavaList(clz);
        return list;
    }

    public static <T> T copy(Object rep, Class<T> clz) {
        JSONObject object = (JSONObject) JSON.toJSON(rep);
        T t = object.toJavaObject(clz);
        return t;
    }


    public static String dateToString(String format, Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String parse = dateFormat.format(date);
        return parse;
    }

    public static String getFileSuffix(String fileName) {
        String substring = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        return substring;
    }

    public static String MD5(String pass) {
        MD5 md5 = MD5.create();
        String s = md5.digestHex(pass, "utf-8");
        return s;
    }

    public static synchronized String generateId() {
        return System.currentTimeMillis() + getRandomNum(6);
    }

    public static synchronized String getRandomNum(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        return sb.toString();
    }

    public static <T> List<T> MapToObj(List<Map<String, Object>> list, Class<T> clz) {
        JSONArray o = (JSONArray) JSON.toJSON(list);
        List<T> list1 = o.toJavaList(clz);
        return list1;
    }


    public static String getCurrentDateStr(String format) {
        return format(new Date(), format);
    }

    public static String format(Date createDate, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(createDate);
    }


    public static Date changeDate(String dateStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = dateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }

    public static String getCurrentDate() {
        return getCurrentDateStr("yyyy-MM-dd HH:mm:ss");
    }

    public static List<Map<String, Object>> getTableNotes(Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<Map<String, Object>> collect = Arrays.stream(fields).map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("key", item.getName());
            ApiModelProperty annotation = item.getAnnotation(ApiModelProperty.class);
            String value = annotation != null ? annotation.value() : item.getName();
            map.put("name", value);
            return map;
        }).collect(Collectors.toList());
        return collect;
    }

    public static boolean notEmpty(String key) {
        return key != null && key.trim().length() > 0;
    }

    public static boolean isNumeric(String str) {
        if (str.trim().length() == 0) return false;
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String getFileName(String file) {
        String substring = file.substring(0, file.lastIndexOf("."));
        return substring;
    }

    public static void copyFile(MultipartFile file, File pdfFile) throws IOException {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            if (!pdfFile.getParentFile().exists()) {
                pdfFile.getParentFile().mkdirs();
            }
            inputStream = file.getInputStream();
            outputStream = new FileOutputStream(pdfFile);
            IoUtil.copy(file.getInputStream(), new FileOutputStream(pdfFile));
        } finally {
            if (outputStream != null) outputStream.close();
            if (inputStream != null) inputStream.close();
        }
    }

    static String ip;
    //获取ip特别占用系统资源，如果频繁获取会导致cpu高负载。
    public static String getIP() {
        if (ip != null) return ip;
        try {
            StringBuilder IFCONFIG = new StringBuilder();
            Enumeration en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                        IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");
                    }
                }
            }
            ip = IFCONFIG.toString();
            return ip;
        } catch (SocketException var6) {
            var6.printStackTrace();
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
                return ip;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                ip = "获取失败";
                return null;
            }
        }
    }
}
